package com.web.wx.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.DocumentException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.tool.HttpRequest;
import com.common.tool.WeiXinUtil;
import com.dao.SettingMemberType;
import com.dao.WeixinSubscribe;
import com.dao.WeixinUnsubscribe;
import com.dao.WeixinUserinfo;
import com.entity.BaseSettingMemberType;
import com.entity.CommonConstant;
import com.entity.weixin.TextMessage;
import com.entity.weixin.WeiXinUserInfo;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;

public class WeiXinInController extends Controller {

    WeiXinUtil weixinUtil = new  WeiXinUtil();
    public void index() {
	System.out.println(this.getRequest().getMethod());
	if ("GET".equalsIgnoreCase(this.getRequest().getMethod())) {
	    validateWeiXinGetRequestion();
	} else {
	    try {
		Map<String, String> map = WeiXinUtil.xmlToMap(getRequest());
		System.out.println(map);
		if (map != null) {
		    String msgType = map.get("MsgType").toString();
		    if ("event".equalsIgnoreCase(msgType)) {
			String event = map.get("Event").toString();
			if ("subscribe".equalsIgnoreCase(event)) {
			    // 订阅时添加一条数据；如果是多次订阅只按最早的一次订阅为主。
			    String recommendUserOpenId = "";
			    if (map.get("Ticket") == null) {
				// 直接扫二维码关注
			    } else {
				// 扫特定用户生成的二维码关注
				String eventKey = map.get("EventKey");
//				recommendUserOpenId = eventKey.split("_")[1].toString();// 推荐人的openid;
				recommendUserOpenId = eventKey;
				recommendUserOpenId = recommendUserOpenId.replace("qrscene_", ""); 
			    }
			    try{
				InsertSubscribeUserInfo(map, recommendUserOpenId);
			    }
			    catch(Exception e){
				renderText("已关注不可重复关注！");
			    }
			    String openId =map.get("FromUserName").toString();
			    insertUserInfo(openId);
			    subscribe(map);
			    
			} else if ("unsubscribe".equalsIgnoreCase(event)) {
			    // 订阅时添加一条数据；如果是多次订阅只按最早的一次订阅为主。
			    unsubscribe(map);
			    System.out.println("欢迎下次再来！");
			    this.renderText("欢迎下次再来！");

			}else if("click".equalsIgnoreCase(event)){
			    String eventKey = map.get("EventKey").toLowerCase();
			    if("V001_MYCARD".equalsIgnoreCase(eventKey)){
				//二维码
//				String openId=map.get("FromUserName").toString();
//				System.out.println("V001_MYCARD:::"+openId);
//				createMyCard(openId);
//				render("mycard.html");
//				this.render("www.baidu.com");
//				renderText("dddddddddd");
				subscribe(map);
			    }
			    if("V1001_MYINFO_SEND".equalsIgnoreCase(eventKey)){
				//个人中心
				String openId=map.get("FromUserName").toString();
				createMyCard(openId);
				render("/weixin/members.jsp");
			    }
			    
			    
			    
			}
		    }
		    if ("text".equalsIgnoreCase(msgType)) {
			reciveAndSendMessge(map);
		    }
		}

	    } catch (IOException e) {
		e.printStackTrace();
	    } catch (DocumentException e) {
		e.printStackTrace();
	    }
	}
    }

    public void createMyCard(String openId) throws UnsupportedEncodingException {
	if (!openId.isEmpty()) {
	    String ticket = Db.queryStr("select myticket from weixin_subscribe where fromusername=?", openId);
	    if (ticket.isEmpty()) {
		WeiXinUtil weiXinUtil = new WeiXinUtil();
		String accessToken = weiXinUtil.getAccessToken();
		ticket = weiXinUtil.getTicketForCreateOwerCard(accessToken, openId);
		Db.update("update weixin_subscribe set myticket=? where fromusername=?", ticket, openId);
		
	    }
	    setAttr("ticket", ticket);
	}
    }

    private void reciveAndSendMessge(Map<String, String> map) {
	String toUserName = map.get("ToUserName");
	String fromUserName = map.get("FromUserName");
	String createTime = map.get("CreateTime");
	String msgType = map.get("MsgType");
	String content = map.get("Content");
	// String msgId=map.get("MsgId");
	String message = null;
	if ("text".equals(msgType)) {
	    TextMessage textMessage = new TextMessage();
	    textMessage.setContent(content);
	    textMessage.setCreateTime(String.valueOf(new Date().getTime()));
	    textMessage.setFromUserName(toUserName);
	    textMessage.setToUserName(fromUserName);
	    textMessage.setMsgType(msgType);
	    message = WeiXinUtil.textMessageToXml(textMessage);
	    System.out.println(message);
	    this.renderText(message);
	}
    }

    private void subscribe(Map<String, String> map) {
	String toUserName = map.get("ToUserName");
	String fromUserName = map.get("FromUserName");
	String message = null;
	TextMessage textMessage = new TextMessage();
	textMessage.setContent(PropKit.get("welcome-words"));
	textMessage.setCreateTime(String.valueOf(new Date().getTime()));
	textMessage.setFromUserName(toUserName);
	textMessage.setToUserName(fromUserName);
	textMessage.setMsgType("text");
	message = WeiXinUtil.textMessageToXml(textMessage);
	this.renderText(message);
    }

    private void unsubscribe(Map<String, String> map) {
	String fromUserName = map.get("FromUserName").toString();

	try {
	    WeixinUnsubscribe weixinUnsubscribe = new WeixinUnsubscribe();	
	    weixinUnsubscribe.setFromusername(map.get("FromUserName").toString());
	    weixinUnsubscribe.setTousername(map.get("ToUserName").toString());
	    weixinUnsubscribe.setCreatetime(map.get("CreateTime").toString());
	    weixinUnsubscribe.setMsgtype(map.get("MsgType").toString());
	    weixinUnsubscribe.setEvent(map.get("Event").toString());
	    weixinUnsubscribe.setMemberstate(CommonConstant.INVALIDATESATE);
	    weixinUnsubscribe.setMembertypecode("");

	    if (map.get("EventKey") != null) {
		weixinUnsubscribe.setEventkey(map.get("EventKey").toString());
	    } else {
		weixinUnsubscribe.setEventkey("");
	    }
	    if (map.get("Ticket") != null) {
		weixinUnsubscribe.setTicket(map.get("Ticket").toString());
	    } else {
		weixinUnsubscribe.setTicket("");
	    }
	    weixinUnsubscribe.setRecommendUsername("");
	    weixinUnsubscribe.save();
	    Db.update("delete from weixin_subscribe where fromusername='"+fromUserName+"'");
	  

	} catch (Exception ex) {
	    System.out.println(ex.getMessage());
	}
    }

    // 验证微信接入
    private void validateWeiXinGetRequestion() {

	String signature = this.getRequest().getParameter("signature");
	String timestamp = this.getRequest().getParameter("timestamp");
	String nonce = this.getRequest().getParameter("nonce");
	String echostr = this.getRequest().getParameter("echostr");
	try {
	    if (signature != null) {
		boolean isCheck = WeiXinUtil.checkSignature(signature, timestamp, nonce, echostr);
		if (isCheck)
		    this.renderText(this.getRequest().getParameter("echostr"));
		else
		    renderText("不是微信调用的");
	    } else {
		renderText("不是微信调用的");
	    }
	} catch (NoSuchAlgorithmException e) {
	    e.printStackTrace();
	}
    }

    // 得到用户信息
    private void getUserInfo(String openid, String accessToken) {
	String url = "https://api.weixin.qq.com/cgi-bin/user/info";
	StringBuilder sb = new StringBuilder().append("access_token=").append(accessToken).append("&openid=")
		.append(openid);
	String s = HttpRequest.sendGet(url, sb.toString());
	System.out.println(s);
	WeiXinUserInfo userInfo = JSON.parseObject(s, WeiXinUserInfo.class);
	System.out.println(userInfo.getCity());
	System.out.println(userInfo.getHeadimgurl());
	this.renderText(s);
    }
    
    
    

    /**
     * 添加关注人信息
     */
    private void InsertSubscribeUserInfo(Map map, String recommendUserOpenId) {
	WeixinSubscribe weixinSubscribe = new WeixinSubscribe();
	weixinSubscribe.setFromusername(map.get("FromUserName").toString());
	weixinSubscribe.setTousername(map.get("ToUserName").toString());
	weixinSubscribe.setCreatetime(map.get("CreateTime").toString());
	weixinSubscribe.setMsgtype(map.get("MsgType").toString());
	weixinSubscribe.setEvent(map.get("Event").toString());
	

	SettingMemberType baseSettingMemberType = new SettingMemberType();
	String sql = "select * from setting_member_type where type_name='普通会员' ";
	baseSettingMemberType = baseSettingMemberType.findFirst(sql);

	String memberTypeCode = baseSettingMemberType.getTypeCode();
	weixinSubscribe.setMembertypecode(memberTypeCode);

	if (map.get("EventKey") != null) {
	    weixinSubscribe.setEventkey(map.get("EventKey").toString());
	} else {
	    weixinSubscribe.setEventkey("");
	}
	if (map.get("Ticket") != null) {
	    weixinSubscribe.setTicket(map.get("Ticket").toString());
	} else {
	    weixinSubscribe.setTicket("");
	}
	weixinSubscribe.setMyticket("");
	weixinSubscribe.setRecommendUsername(recommendUserOpenId);	
	weixinSubscribe.save();
	
    }

    private void createOwerCard(String accessToken, String openid) throws UnsupportedEncodingException {
	System.out.println("createOwerCard");

	JSONObject json = new JSONObject();

	// String
	// url="https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token="+accessToken;
	// json.put("openid", openid);
	// json.put("remark", "pangzi");

	String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
	Map map = new HashMap();
	Map mapscene = new HashMap();
	map.put("scene_str", openid);
	mapscene.put("scene", map);
	json.put("expire_seconds", 604800);
	json.put("action_name", "QR_LIMIT_STR_SCENE");
	json.put("action_info", mapscene);

	System.out.println(json.toJSONString());
	String s = HttpRequest.senPost(url, json);
	System.out.println(s);
	Map relMap = WeiXinUtil.getMapFromJson(s);

	String ticket = relMap.get("ticket").toString();
	System.out.println(ticket);

	// url = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
	// StringBuilder sb = new StringBuilder().append("ticket=")
	// .append(URLEncoder.encode(ticket, "utf-8"));

	// http请求方式: POST
	// URL:
	// https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
	// POST数据格式：json
	// POST数据例子：{"expire_seconds": 604800, "action_name": "QR_SCENE",
	// "action_info": {"scene": {"scene_id": 123}}}
    }

    
    
    private void insertUserInfo(String openId)
    {
	WeiXinUserInfo userInfo =weixinUtil.getUserInfo(openId);
	WeixinUserinfo suser = new WeixinUserinfo();
	suser.setNickname(userInfo.getNickname());
	suser.setCity(userInfo.getCity());
	suser.setCountry(userInfo.getCountry());
	suser.setGroupid(userInfo.getGroupid());
	suser.setHeadimgurl(userInfo.getHeadimgurl());
	suser.setLanguage(userInfo.getLanguage());
	suser.setOpenid(userInfo.getOpenid());
	suser.setProvince(userInfo.getProvince());
	suser.setRemark(userInfo.getSex());
	suser.setSubscribe(userInfo.getSubscribe());
	suser.save();
	
    }
    
   
    // //发送 GET 请求
    // String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString",
    // "key=123&v=456");
    // System.out.println(s);
    //
    // //发送 POST 请求
    // String
    // sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString",
    // "key=123&v=456");
    // System.out.println(sr);

}
